<template>
  <div class="knowledge-mould">
    <div class="header">
      <div class="tabs_box">{{ title }}</div>
      <div class="update-time">上次保存时间：{{ modifyTime || list.modifyTime }}</div>
      <div class="save" @click="saveClick">
        <i class="iconfont iconbaocun1"></i>
        <span>{{ saveLoading ? '保存中...' : isChanged ? '已更改' : '自动保存...' }}</span>
      </div>
      <div class="btns" >
        <el-button round @click="syncHandout" v-if="showSyncBtn">同步变更到讲义</el-button>
      </div>
    </div>
    <div class="content">
      <EditorComponent :knowledgeData="data" />
      <ToolbarComponent />
      <EditContent v-loading="editorLoading" :knowledgeData="data" :subjectId="subjectId"/>
    </div>
  </div>
</template>

<script lang="ts">
import { ref, computed, watch } from 'vue';
import QuestionDirective from './../../utils/question.directive';
import EditContent from "./edit-content.vue";
import ToolbarComponent from "./toolbar.vue";
import EditorComponent from "./editor.vue";
import store from './store/index';
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus';
import $, { emitter } from '$'

export default{
  props: {
    data: {
      type: Object,
      default: () => ({})
    },
    subjectId: String
  },
  components: { EditContent, ToolbarComponent, EditorComponent },
  directives: {
    question: QuestionDirective
  },
  setup(props) {
    let knowledgeData = props.data
    let list = ref()
    list = props.data
    let modifyTime = ref()
    let title = computed(() => store.state.title)
    store.commit('set_knowledge_moduleId', props.data.id);
    let saveLoading = ref(false);
    let isChanged = ref(false);
    let isReady = false;
    emitter.on('knowledge-element-change',() => {
      if (isReady) {
        isChanged.value = true;
        autoSave();
      }
    });

    const syncHandout = async() => {
      ElMessageBox.confirm('是否替换所有公共讲义中的内容？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        $.http.post('/admin/handoutNode/batchUpdateHandoutKnowledge', { knowledgeId: props.data.id }).then(res => {
          res.result && ElMessage.success('同步成功！')
          !res.result && ElMessage.warning(res.msg)
        })
      })
    }

    const autoSave = $.debounce(() => save(), 170)
    let paperInfo: any = computed(() => store.state.paperInfo);
    let showSyncBtn = ref(false)
    watch(() => paperInfo.value.content, (newValue, oldValue) => {
      if (oldValue.length) {
        showSyncBtn.value = true
      } else {
        showSyncBtn.value = false
      }
    }, { immediate: false, deep: true })
    const save = () => {
      saveLoading.value = true;
      $.http.json('/admin/knowledgeContent/batchSave', paperInfo.value.content).then(res => {
        saveLoading.value = false;
        isChanged.value = false;
      })
    }
    const saveClick = () => {
      saveLoading.value = true;
      let newList = $.clone(paperInfo.value.content)
      paperInfo.value.saveData.map(item => {
        newList.map((editorItem, idx) => {
          if (editorItem.id === item.id) {
            newList[idx] = item
          }
        })
      })
      $.http.json('/admin/knowledgeContent/batchSave', newList).then(res => {
        saveLoading.value = false;
        isChanged.value = false;
      })
    }
    emitter.on('refresh-change',() => {
      if (isReady) {
        isChanged.value = true;
        refreshSave();
      }
    });
    // 需要获取id，先进行一次保存并刷新接口
    const refreshSave = $.debounce(() => reSave(), 170)
    const reSave = () => {
      saveLoading.value = true;
      $.http.json('/admin/knowledgeContent/batchSave', paperInfo.value.content).then(res => {
        init()
        isReady = false
        saveLoading.value = false;
        isChanged.value = false;
      })
    }
    //正则去掉 html标签
    const removeHtml = (data) => {
      let reg = /(<(.[^>]*)>)|(&nbsp;)/g;
      if (data) {
        data = data.replace(/<img[^>]*>/g, '[图片]').replace(/<table[^>]*>?.*<\/table>/g, '[表格]').replace(reg, '')
      }
      return data
    }
    //左侧数据排序
    emitter.on('sort-change',(data) => sort(data))
    const sort = (data) => {
      let sortData = $.clone(data)
      sortData.map(item => {
        item.child = []
      })
      let noParentData = sortData.filter(p => !p.pid)
      noParentData.map(fatherItem => {
        sortData.map(item => {
          item.content = removeHtml(item.content)
          item.cssTitle = removeHtml(item.cssTitle)
          item.content && (item.content = item.content.replace(/\&nbsp;/g, " "))
          fatherItem.id === item.pid && fatherItem.child.push(item)
        })
      })
      store.commit('set_sort_data', noParentData);
    }
    emitter.on('pid-change',(data) => changePid(data))
     //生成pid 用来改变时使用
    const changePid = (data) => {
      data.map((item, idx) => {
        if (item.type === 2 || item.type === 4) {
          if (idx > 0 && data[idx - 1].type === 8) {
            data.map((newItem) => {
              newItem.id === data[idx - 1].pid && (item.pid = newItem.pid)
            })
          } else if (idx > 0) {
            data[idx - 1].pid? item.pid = data[idx - 1].pid : (data[idx - 1].type === 4 || data[idx - 1].type === 2)? null : item.pid = data[idx - 1].id
          } else if (idx === 0) {
            item.pid = null
          }
        } else if (item.type === 8) {
          data[idx - 1].type === 4 ? item.pid = data[idx - 1].id : data[idx - 1].type === 8 ? item.pid = data[idx - 1].pid : null
        }
      })
      return data
    }
    //题目排序
    emitter.on('change-data',(data) => changeData(data))
    const changeData = (data) => {
      data = changePid(data)
      let knowledge:any = data.filter(p => p.type === 3)//类型为知识点时序号
      let question:any = data.filter(p => p.type === 4) //类型为例题时序号
      let changeQues:any = data.filter(p => p.type === 8) //类型为例题时序号
      let practiceQues:any = data.filter(p => p.type === 9) //类型为练习题时序号
      data.map((item) => {
        knowledge.map((knowItem, knowIdx) => {
          knowItem.index = knowIdx + 1
          item.id === knowItem.id && (item = knowItem)
        })
        question.map((quesItem, quesIdx) => {
          quesItem.index = quesIdx + 1
          item.id === quesItem.id && (item = quesItem)
        })
        practiceQues.map((quesItem, quesIdx) => {
          quesItem.index = quesIdx + 1
          item.id === quesItem.id && (item = quesItem)
        })
        let newChangeList: any[] = []
        changeQues.map((changeItem) => {
          if (changeItem.pid === item.id) {
            changeItem.index = item.index
            newChangeList.push(changeItem)
          }
          item.id === changeItem.id && (item = changeItem)
        })
        newChangeList.map((newItem, newIdx) => {
          newItem.title = newIdx + 1
          item.id === newItem.id && (item = newItem)
        })
      })
      return data
    }
    const loading = ElLoading.service();
    let editorLoading = ref(false)
    const init = () => {
      editorLoading.value = true
      $.http.post('/admin/knowledgeContent/queryContent', { moduleId: props.data.id, templateId: props.data.templateId }).then((res) => {
        res.json = changeData(res.json)
        store.commit('set_paper_init', res.json);
        sort(res.json)
        loading.close();
        editorLoading.value = false
        setTimeout(() => isReady = true );
      });
    }
    init()

    return { list, isChanged, saveLoading, save, modifyTime, knowledgeData, sort, changePid, title, removeHtml, changeData, saveClick, editorLoading, syncHandout, showSyncBtn }
  }
}
</script>

<style lang="scss" scoped>
.knowledge-mould {
  background: #F4F5F9;
  padding-bottom: 1px;
  height: 100%;
  .cus__empty__container {
    margin: 0 auto;
  }
  .header {
    background: $--color-primary;
    padding: 0 80px;
    display: flex;
    height: 60px;
    line-height: 60px;
    color: #fff;
    .tabs_box {
      font-size: 16px;
    }
    .update-time {
      margin-left: auto;
      margin-right: 10px;
    }
    .save {
      cursor: pointer;
      margin-left: 10px;
      & > i {
        margin-right: 10px;
      }
    }
    .btns {
      margin-left: 20px;
      button {
        color: #72b22a;
        padding: 10px 23px;
      }
    }
  }
  & > .content {
    flex: 1 1 60px;
    position: relative;
    height: calc(100% - 100px);
  }
  .toolbar {
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }
}
</style>
